on(window, 'load', function () {
  function getScore() {
    window.fetch('/api/score')
    .then(res => res.json())
    .then(res => {
      const bestScore = res.data[0].score

      $('.best-container .score')[0].innerHTML = bestScore
      data.best = bestScore
      data.list = res.data

      // code 0 已登录，201 未登录 202 登录过期
      if (res.code === 0) {
        $('.subtitle')[0].style = "display:none"
      } else {
        $('.subtitle')[0].style = "display:block"
      }
    })
  }
  getScore()
})

function showLoginModel () {
  $('.login-container')[0].style = 'display: block'
}

function hideLoginModel () {
  $('.login-container')[0].style = 'display: none'
}

function getCode() {
  let s = 60
  window.fetch('/api/send_code?email='+$('#email')[0].value)
    .then(res => res.json())
    .then(res => {
      if(res.code !== 0) {
        return alert(res.msg)
      }
      $('.code')[0].disabled = true
      countTime(s)
    })
}

function countTime (s)  {
  const d = $('.code')[0]
  if(s <= 0){
    d.disabled = false
    d.innerHTML = '获取验证码'

    return
  }
  const ti = setTimeout(() => {
    d.innerHTML = s+'秒后重试'
    s--
    countTime(s)
  }, 1000)
}

function login() {
  const email = $('#email')[0].value
  const code = $('#code')[0].value
  window.fetch('/api/login', {
    method: 'post',
    headers: {
      'content-type': 'application/json'
    },
    body: JSON.stringify({
      email,
      code,
      score: data.score || undefined
    })
  }).then(res => res.json())
    .then(res => {
      if(res.code !== 0) {
        return alert(res.msg)
      }
      console.log(res)
      hideLoginModel()
      if(data.score){
        $('.best-container .score')[0].innerHTML = data.score
      }
      data.best = data.score
      $('.subtitle')[0].style = "display:none"
      // $('.code')[0].disabled = true
      // countTime(s)
    })
}

function Ranking() {
  let table = document.createElement("table");
  table.style = 'width: 80%; margin: 10%;'
  str = `<tr>
            <th>排名</th>
            <th>邮箱</th>
            <th>得分</th>
          </tr>`
  data.list.forEach((itm, idx) => {
    str += `<tr>
              <td>${idx + 1}</td>
              <td>${itm.email}</td>
              <td>${itm.score}</td>
            </tr>`
  })

  table.innerHTML = str
  swal({
    title: '排行榜',
    content: table,
    button: "关闭",
  });
}